<template>
  <el-col class="app-v-center app-column app-flex-1" style="overflow-y: auto">
    <el-row
      class="app-h-56px app-fill-width app-h-end app-v-center px-4 app-bb-1px-l2"
      :gutter="10"
    >

      <!-- <el-col :span="6"> -->
      <el-select v-model="lapsCount" class="mr-2" placeholder="请选择圈数" @change="getDataList">
        <el-option
          key="v0"
          label="全部"
          :value="undefined"
        />
        <el-option
          key="v1"
          label="1圈"
          :value="1"
        />
        <el-option
          key="v2"
          label="2圈"
          :value="2"
        />
        <el-option
          key="v3"
          label="3圈"
          :value="3"
        />
      </el-select>
      <!-- </el-col> -->
      <!-- <el-col :span="6" class="mr-2"> -->
      <el-select v-model="competitionId" class="mr-2" placeholder="请选择赛事" @change="getDataList">
        <el-option
          v-for="c in compitetionList"
          :key="c.id"
          :label="c.name"
          :value="c.id"
        />
      </el-select>
      <!-- </el-col> -->
      <el-button
        type="primary"
        @click="editInfo()"
      >修改排行榜界面信息<i
        class="el-icon-edit"
      /></el-button>
      <el-button type="primary" @click="addRanking()">添加参与者</el-button>
    </el-row>
    <el-table
      :data="dataList"
      class="app-flex-1"
      style="width: 100%; overflow-y: auto"
      @sort-change="sortChange"
    >
      <el-table-column sortable="custom" align="center" prop="no" label="编号" />
      <el-table-column prop="name" align="center" label="选手">
        <template slot-scope="scope">
          <div class="app-v-center app-column">
            <img
              :src="scope.row.imageUrl || require('@/assets/icon.jpg')"
              style="width: 40px; height: 40px; border-radius: 50%"
              alt=""
            >
            <div class="mt-2">
              {{ scope.row.name }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="lapsCount" label="圈数" />
      <el-table-column v-if="!lapsCount || lapsCount >= 1" align="center" prop="speed" label="第一圈">
        <template slot-scope="scope">
          <span v-if="scope.row.speed">
            {{ scope.row.speed === -1 ? 'DNF' : scope.row.speed.toFixed(2)+ '秒' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column v-if="!lapsCount || lapsCount >= 2" align="center" prop="speedTwo" label="第二圈">
        <template slot-scope="scope">
          <span v-if="scope.row.speedTwo">
            {{ scope.row.speedTwo === -1 ? 'DNF' : scope.row.speedTwo.toFixed(2)+ '秒' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column v-if="!lapsCount || lapsCount === 3" align="center" prop="speedThree" label="第三圈">
        <template slot-scope="scope">
          <span v-if="scope.row.speedThree">
            {{ scope.row.speedThree === -1 ? 'DNF' : scope.row.speedThree.toFixed(2)+ '秒' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" align="center" prop="speedTotal" label="总时间">
        <template slot-scope="scope">
          <span v-if="scope.row.speedTotal">
            {{ scope.row.speedTotal === -1 ? 'DNF' : scope.row.speedTotal.toFixed(2)+ '秒' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="action" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="error"
            @click="editRanking(scope.row)"
          >修改</el-button>
          <el-button
            size="small"
            type="warning"
            @click="deleteRanking(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mb-10 mt-5"
      style="max-width: 100vw"
      background
      :current-page.sync="pageNo"
      :page-sizes="[10, 20, 50]"
      :page-size.sync="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="getDataList"
      @current-change="getDataList"
    />

    <el-dialog
      title="修改介绍信息"
      :visible.sync="showInfoDialog"
      width="800px"
    >
      <div>
        <el-form
          ref="form"
          :model="info"
          :rules="rules"
          label-width="120px"
          class="app-flex-1"
        >
          <el-form-item label="名字" prop="name">
            <el-input v-model="info.name" />
          </el-form-item>
          <el-form-item label="背景" prop="bgImage">
            <el-upload
              :multiple="false"
              :show-file-list="false"
              :action="`${host}/upload`"
              :on-success="handleBgSuccess"
            >
              <div class="bg-uploader uploader">
                <img v-if="info.bgImage" :src="info.bgImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer app-h-end">
          <el-button @click="showInfoDialog = false">取 消</el-button>
          <el-button type="primary" @click="updateSetting">确认</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :title="isEdit ? '编辑参赛人' : '添加参赛人'"
      :visible.sync="showRankingDialog"
      width="800px"
    >
      <el-form
        ref="rankingForm"
        :model="rankingInfo"
        :rules="rules"
        label-width="120px"
        class="app-flex-1"
      >
        <el-form-item label="比赛" prop="competitionId">
          <el-select v-model="rankingInfo.competitionId" class="mr-2" placeholder="请选择赛事">
            <el-option
              v-for="c in compitetionList"
              :key="c.id"
              :label="c.name"
              :value="c.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            :multiple="false"
            :show-file-list="false"
            :action="`${host}/upload`"
            :on-success="handleAvatarSuccess"
          >
            <div class="avatar-uploader uploader">
              <img v-if="rankingInfo.imageUrl" :src="rankingInfo.imageUrl">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="圈数" prop="lapsCount">
          <el-select v-model="rankingInfo.lapsCount">
            <el-option
              v-for="l in lapList"
              :key="l.id"
              :label="l.label"
              :value="l.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选手名字" prop="name">
          <el-input v-model="rankingInfo.name" />
        </el-form-item>
        <el-form-item label="选手编号" prop="no">
          <el-input v-model.number="rankingInfo.no" type="number" />
        </el-form-item>
        <el-form-item label="第一圈（秒）" prop="speed">
          <el-row>
            <el-col :span="20">
              <el-input v-model.trim.number="rankingInfo.speed" :disabled="speedDNF" type="number" />
            </el-col>
            <el-col :span="4" class="app-h-center">
              <el-checkbox v-model="speedDNF">DNF</el-checkbox>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="第二圈（秒）" prop="speed">
          <el-col :span="20">
            <el-input v-model.trim.number="rankingInfo.speedTwo" :disabled="speedTwoDNF" type="number" />
          </el-col>
          <el-col :span="4" class="app-h-center">
            <el-checkbox v-model="speedTwoDNF">DNF</el-checkbox>
          </el-col>
        </el-form-item>
        <el-form-item label="第三圈（秒）" prop="speed">
          <el-col :span="20">
            <el-input v-model.trim.number="rankingInfo.speedThree" :disabled="speedThreeDNF" type="number" />
          </el-col>
          <el-col :span="4" class="app-h-center">
            <el-checkbox v-model="speedThreeDNF">DNF</el-checkbox>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer app-h-end">
        <el-button @click="showRankingDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitRankingInfo">确认</el-button>
      </div>
    </el-dialog>
  </el-col>
</template>

<script>
import {
  getRankingList,
  getConfig,
  addRanking,
  deleteRanking,
  updateSetting,
  getCompetitionList
} from '@/api/user'
import { host } from '@/utils/request'
export default {
  data: () => {
    const checkNo = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('编号不能为空'))
      }
      setTimeout(() => {
        const v = parseInt(value)
        if (!Number.isInteger(v) || v < 100000 || v > 999999) {
          callback(new Error('请输入6位数'))
        } else {
          callback()
        }
      })
    }
    return {
      host,
      rules: {
        // name: [{ required: true, message: '请输入名字', trigger: 'blur' }],
        userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        no: [{ validator: checkNo ,trigger: 'change' }],
        lapsCount: [{ required: true, message: '请选择圈速编号', trigger: 'blur' }]
      },
      isEdit: false,
      showInfoDialog: false,
      showRankingDialog: false,
      info: {
        avatar: '',
        bgImage: '',
        directSeeding: '',
        introduction: '',
        space: ''
      },
      rankingInfo: {
        competitionId: null,
        id: undefined,
        imageUrl: '',
        lapsCount: null,
        name: null,
        no: null,
        speed: null,
        speedTwo: null,
        speedThree: null
      },
      speedThreeDNF: false,
      speedTwoDNF: false,
      speedDNF: false,
      dataList: [],
      compitetionList: [],
      lapList: [{
        label: '1圈',
        value: 1
      },{
        label: '2圈',
        value: 2
      },{
        label: '3圈',
        value: 3
      }],
      competitionId: null,
      lapsCount: null,
      searchText: undefined,
      desc: undefined,
      type: undefined,
      pageNo: 1,
      pageSize: 10,
      total: 0
    }
  },
  mounted() {
    this.getDataList()
    this.getDataConfig()
    getCompetitionList({ pageNo: 1,pageSize: 999 }).then((res) => {
      if (res.code === 200) {
        this.compitetionList = res.data.dataList
      }
    })
  },
  methods: {
    getDataConfig() {
      getConfig().then((res) => {
        if (res.code === 200) {
          this.info = Object.assign({},this.info, res.data || {})
        }
      })
    },
    editInfo() {
      this.showInfoDialog = true
    },
    handleAvatarSuccess(a, b, c, d) {
      this.rankingInfo.imageUrl = host + a
    },
    handleBgSuccess(a, b, c, d) {
      this.info.bgImage = host + a
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    updateSetting() {
      updateSetting(this.info).then((res) => {
        if (res.code === 200) {
          this.getDataConfig()
          this.showInfoDialog = false
          this.$message.success('修改成功')
        }
      })
    },
    addRanking() {
      this.isEdit = false
      this.rankingInfo = {
        competitionId: null,
        id: undefined,
        imageUrl: '',
        lapsCount: null,
        name: null,
        no: null,
        speed: null,
        speedTwo: null,
        speedThree: null
      }
      this.speedDNF = false
      this.speedTwoDNF = false
      this.speedThreeDNF = false
      this.showRankingDialog = true
      this.$nextTick(() => {
        this.$refs.rankingForm.clearValidate()
      })
    },
    editRanking(item) {
      this.isEdit = true
      this.rankingInfo = { ...item }
      this.speedDNF = this.rankingInfo.speed === -1
      this.speedTwoDNF = this.rankingInfo.speedTwo === -1
      this.speedThreeDNF = this.rankingInfo.speedThree === -1
      this.rankingInfo.speed === -1 ? this.rankingInfo.speed = null : void 0
      this.rankingInfo.speedTwo === -1 ? this.rankingInfo.speedTwo = null : void 0
      this.rankingInfo.speedThree === -1 ? this.rankingInfo.speedThree = null : void 0
      this.showRankingDialog = true
      this.$nextTick(() => {
        this.$refs.rankingForm.clearValidate()
      })
    },
    deleteRanking(item) {
      this.$confirm(`确认删除参赛人： ${item.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRanking(item.id).then((res) => {
            if (res.code === 200) {
              this.getDataList()
              this.$message.success('删除成功')
            }
          })
        })
        .catch(() => {})
    },
    submitRankingInfo() {
      this.$refs.rankingForm.validate(valid => {
        if (valid) {
          this.rankingInfo.speed = this.speedDNF ? -1 : this.rankingInfo.speed
          this.rankingInfo.speedTwo = this.speedTwoDNF ? -1 : this.rankingInfo.speedTwo
          this.rankingInfo.speedThree = this.speedThreeDNF ? -1 : this.rankingInfo.speedThree
          addRanking(this.rankingInfo).then((res) => {
            if (res.code === 200) {
              if (this.rankingInfo.id) {
                this.$message.success('修改成功')
              } else {
                this.$message.success('添加成功')
              }
              this.showRankingDialog = false
              this.pageNo = 1
              this.getDataList()
            }
          })
        }
      })
    },
    sortChange(column) {
      if (!column.order) {
        this.desc = undefined
      } else if (column.order === 'ascending') {
        if (column.prop === 'no') {
          this.desc = 1
        } else {
          this.desc = 3
        }
      } else {
        if (column.prop === 'no') {
          this.desc = 2
        } else {
          this.desc = 4
        }
      }
      this.getDataList()
    },
    getDataList() {
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        name: this.searchText,
        desc: this.desc,
        competitionId: this.competitionId,
        lapsCount: this.lapsCount
      }
      getRankingList(params).then((res) => {
        if (res.code === 200) {
          this.dataList = res.data.dataList
          this.total = res.data.total
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader {
  width: 80px;
  height: 80px;
}
.bg-uploader {
  width: 160px;
  height: 160px;
}

.uploader {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.uploader img {
  width: 100%;
  height: 100%;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
</style>
